package com.huitone.smspfm.oldclient.store;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import com.huitone.smspfm.oldclient.app.AppStaticConfigs;
import com.huitone.smspfm.oldclient.logger.ExtLogger;
import com.bin.common.utils.FileUtils;
import com.bin.common.utils.StringUtils;
import com.huitone.smspfm.oldclient.model.MtSms;

/**   
* @Title MtTmpStore.java 
* @Package com.huitone.smspfm.oldclient.module.mt 
* @Description TODO(用一句话描述该文件做什么) 
* @author ybliang   
* @date 2017年5月26日 下午4:44:42 
* @version V1.0   
*/
public class MtTmpStore implements Serializable {
	
	private static final long serialVersionUID = 1L;
	
	private final static ExtLogger logger = ExtLogger.create(MtTmpStore.class);
	
	private static Map<String, MtSms> tmpStore = new ConcurrentHashMap<String, MtSms>();
	
	/*private class PLock {}
	private class RLock {}*/
	
	public static void put(String key, MtSms value) {
		tmpStore.put(key, value);
	}
	
	public static void remove(String key) {
		tmpStore.remove(key);
	}
	
	public synchronized static List<MtSms> getOutTimes(long timeInteval) {
		List<MtSms> list = new ArrayList<>();
		Iterator<Entry<String, MtSms>> iterator = tmpStore.entrySet().iterator();
		while(iterator.hasNext()) {
			Entry<String, MtSms> entry = iterator.next();
			MtSms mtSms = entry.getValue();
			Date lastSendTime = mtSms.getLastSendTime();
			if (lastSendTime == null) {
				entry.getValue().setLastSendTime(new Date());
			} else {
				long lastTime = lastSendTime.getTime();
				long currTime = System.currentTimeMillis();
				if (currTime - lastTime >= timeInteval) {
					list.add(mtSms);
					entry.getValue().setiSendTimes(mtSms.getiSendTimes() + 1);
					entry.getValue().setLastSendTime(new Date());
				}
			}
		}
		return list;
	}
	
	public static void storeSerialize() {
		BufferedOutputStream bos = null;
		ObjectOutputStream oos = null;
		try {
			File file = null;
			if (!StringUtils.isEmpty(AppStaticConfigs.mtTmpStoreFile)) {
				try {
					file = FileUtils.createFile(AppStaticConfigs.mtTmpStoreFile);
				} catch (Exception e) {
					logger.error("创建文件失败,将使用默认路径下的mtTmpStore文件", e);
				}
			}
			
			if (file == null) {
//				file = FileUtils.createFile(FileUtils.getJarParentPath(MtSms.class)+"/store/mttmpstore.dat");
				file = FileUtils.createFile(FileUtils.getJarParentPath(MtSms.class)+File.separator +"store"+File.separator+"mttmpstore.dat");
			}
			
		    bos = new BufferedOutputStream(new FileOutputStream(file));
		    oos = new ObjectOutputStream(bos);
		    oos.writeObject(tmpStore);
		    oos.flush();
		    oos.close();
		    logger.info("write object success! storeSize:" + tmpStore.size());
		} catch (IOException e) {
		    logger.error("write object failed!", e);
		} finally {
			if (oos != null) {
				try {
					oos.close();
				} catch (IOException e) {
					logger.error(e);
				}
			}
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					logger.error(e);
				}
			}
		}
	}
	
	@SuppressWarnings("unchecked")
	public static void storeDeSerialize() {
		
		BufferedInputStream bis = null;
		ObjectInputStream ois = null;
		try {
			
			File file = null;
			if (!StringUtils.isEmpty(AppStaticConfigs.mtTmpStoreFile)) {
				try {
					file = FileUtils.createFile(AppStaticConfigs.mtTmpStoreFile);
				} catch (Exception e) {
					logger.error("创建文件失败,将使用默认路径下的mtTmpStore文件", e);
				}
			}
			
			if (file == null) {
//				file = FileUtils.createFile(FileUtils.getJarParentPath(MtSms.class)+"/store/mttmpstore.dat");
				file = FileUtils.createFile(FileUtils.getJarParentPath(MtSms.class)+File.separator +"store"+File.separator+"mttmpstore.dat");
			}
			
			bis = new BufferedInputStream(new FileInputStream(file));
			ois = new ObjectInputStream(bis);
			tmpStore = (Map<String, MtSms>) ois.readObject();
		    logger.info("read object success! storeSize:" + tmpStore.size());
		} catch (EOFException e) {} catch (IOException | ClassNotFoundException e) {
		    logger.error("read object failed!", e);
		} finally {
			if (ois != null) {
				try {
					ois.close();
				} catch (IOException e) {
					logger.error(e);
				}
			}
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					logger.error(e);
				}
			}
		}
	}
}
